

use salvo::prelude::*;
use crate::{web::{WebResult, ResponseError, ResponseResult}, db};
use super::entity::User;



// /user/register
// post
#[handler]
pub async fn register(request: &mut Request) -> WebResult<Option<u8>>
{
    let result = request.parse_json::<User>().await;
    if result.is_err() {
        return Err(ResponseError::json_parse_error(result.unwrap_err().to_string()))
    }
    let user_req = result.unwrap();
    
    let mut nickname = String::from(user_req.get_username());
    if user_req.get_nickname().is_none() {
        nickname = user_req.get_username().to_string();
    }
    let user = User::new(
        nickname,
        user_req.get_username().to_string(),
        user_req.get_password().to_string()
    );

    let result = User::select_by_username(db::get_rbatis(), user.get_username()).await;
    if result.is_err() {
        return Err(ResponseError::database_error());
    }
    let option = result.unwrap();
    if option.is_some() {
        return Ok(ResponseResult::failed("用户名已被使用".to_string(), Option::None));
    }

    let result = User::insert(db::get_rbatis(), &user).await;
    if result.is_err() {
        return Err(ResponseError::database_error());
    }

    Ok(ResponseResult::success("注册成功".to_string(), Option::None))
}


#[handler]
pub async fn login(request: &mut Request) -> WebResult<Option<u8>>
{
    let result = request.parse_json::<User>().await;
    if result.is_err() {
        return Err(ResponseError::json_parse_error(result.unwrap_err().to_string()))
    }
    let user_req = result.unwrap();
    let result = User::select_by_username(db::get_rbatis(), user.get_username()).await;
    if result.is_err() {
        return Err(ResponseError::database_error());
    }
    let option = result.unwrap();
    if option.is_none() {
        return Ok(ResponseResult::failed("不存在的用户".to_string(), Option::None));
    }
    let original = option.unwrap();
    if user_req.get_password() != original.get_password() {
        return Ok(ResponseResult::failed("密码错误".to_string(), Option::None));
    }

    Ok(ResponseResult::success("登录成功".to_string(), Option::None))
}





